package com.jl.controller;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONArray;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.excel.DeviceExcel;
import com.jl.commons.result.ResultData;
import com.jl.commons.utils.BASE64;
import com.jl.model.DataFile;
import com.jl.service.IDataFileService;
import com.jl.service.IDeviceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/file")
public class FileUploadController extends BaseController {

    @Autowired
    private IDataFileService dataFileService;

    @Autowired
    private IDeviceService deviceService;


    /**
     * 上传资料内容里面的图片文件
     *
     * @param dataFileImage
     * @return
     */
    @PostMapping("uploadDataFileImage")
    @ResponseBody
    public Object uploadImage(HttpServletRequest request, MultipartFile dataFileImage) throws IOException {

        String path = request.getServletContext().getRealPath("/");
        //   String path = ResourceUtils.getURL("classpath:").getPath();
        path = path + Constants.DATA_FILE_IMAGE_DIR;


        File rootPath = new File(path);
        if (!rootPath.exists()) {
            rootPath.mkdirs();
        }
        if (!path.endsWith("/")) {
            path = path + "/";
        }

        Map<String, Object> map = new HashMap<>();
        if (null != dataFileImage) {
            File file = new File(path + dataFileImage.getOriginalFilename());
            dataFileImage.transferTo(file);
        }
        map.put("errno", 0);
        List<String> imageList = new ArrayList<>();
        imageList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553708079635&di=8c5f6a12b9adeb4c5acc7c91da7fb446&imgtype=0&src=http%3A%2F%2Fblog.mgyun.com%2Fwp-content%2Fuploads%2F2013%2F02%2Fbaidu-yun-logo2.jpg");
        map.put("data", imageList);
        return map;
    }


    /**
     * 上传资料的文件文件
     *
     * @param file
     * @return
     */
    @PostMapping("uploadDataFile")
    @ResponseBody
    public Map<String, Object> uploadFiles(HttpServletRequest request, HttpServletResponse reponse, MultipartFile file) throws FileNotFoundException {
        // String path = ResourceUtils.getURL("classpath:").getPath();
        String path = request.getServletContext().getRealPath("/");
        path = path + Constants.DATA_FILE_DIR;
        File rootPath = new File(path);
        if (!rootPath.exists()) {
            rootPath.mkdirs();
        }
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        //如果上传后，出现文件下载框 要在服务端对response的header设置 Content-Type: text/html
        reponse.setHeader("Content-Type", "text/html");
        Map<String, Object> map = new HashMap<>();
        if (null != file) {
            File copyFile = new File(path + file.getOriginalFilename());
            try {
                file.transferTo(copyFile);
                map.put("code", 0);
                map.put("msg", "success");
                System.out.println(file.getOriginalFilename());
                map.put("data", file.getOriginalFilename());
                return map;
            } catch (IOException e) {
                map.put("code", 1);
                map.put("msg", "文件获取异常");
                map.put("data", null);
                e.printStackTrace();
                return map;
            }
        }
        map.put("code", 1);
        map.put("msg", "系统异常");
        map.put("data", null);
        return map;
    }

    @GetMapping("downloadDataFile")
    public ResponseEntity<byte[]> downloadDataFile(HttpServletRequest request, Long dataFileId) {
        DataFile dataFile = dataFileService.getById(dataFileId);
        String downloadUrl = null;
        String downFileName = null; // 文件名称的编码
        InputStream in = null;
        byte[] body = null;
        try {
            downFileName = new String(dataFile.getFileUrl().getBytes("utf8"), "ISO-8859-1");
            // downloadUrl = ResourceUtils.getURL("classpath:").getPath();
            downloadUrl = request.getServletContext().getRealPath("/");
            downloadUrl = downloadUrl + Constants.DATA_FILE_DIR;

            File file = new File(downloadUrl + dataFile.getFileUrl());
            in = new FileInputStream(file);
            body = new byte[in.available()];
            in.read(body);

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", "attachment; filename=" + downFileName);
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));

            return org.springframework.http.ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(body);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return org.springframework.http.ResponseEntity.status(ErrorCode.ERROR).build();
    }

    @PostMapping("previewDataFile")
    @ResponseBody
    public ResultData previewDataFile(HttpServletRequest request, Long dataFileId) {
        DataFile dataFile = dataFileService.getById(dataFileId);
        String BaseUrl = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort()
                + request.getContextPath() + "/";
        if (null != dataFile && StringUtils.isNotBlank(dataFile.getFileUrl())) {
            BaseUrl = BaseUrl + Constants.DATA_FILE_DIR + dataFile.getFileUrl();
            return success(BaseUrl);
        } else {
            return fail();
        }
    }

    @GetMapping("ignDeviceExport")
    public void exportDeviceExcel(HttpServletRequest request, HttpServletResponse response,String json) {
        String value = BASE64.decode(json);
        List<Long> ids = JSONArray.parseArray(value,Long.class);
        ServletOutputStream out = null;
        try {
            String fileName = new String(("DeviceList-" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
                    .getBytes(), "UTF-8");
            String downFileName = new String(fileName.getBytes("utf8"), "ISO-8859-1");
            //返回头一定要写在 out = response.getOutputStream();之前，不然下载就是zip文件有问题
            //response.setContentType("multipart/form-data");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + downFileName + ".xlsx");
            out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            Sheet sheet1 = new Sheet(1, 0, DeviceExcel.class);
            sheet1.setSheetName("sheet");
            List<DeviceExcel> list = deviceService.selectDeviceExcelByIds(ids);
            writer.write(list, sheet1);
            writer.finish();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

